<script setup lang="ts">
import { ref, computed } from 'vue';
import {
	resolveDomain,
	getDnsRecordByType,
	isValidDomain,
	cleanDomain,
	type DomainInfo,
	type DnsRecord
} from './domain-resolver.service';

const domain = ref('');
const domainInfo = ref<DomainInfo | null>(null);
const loading = ref(false);
const error = ref<string | null>(null);
const loadingStep = ref<string>('');

// DNS记录相关状态
const selectedDnsType = ref<string>('A');
const dnsRecords = ref<DnsRecord[]>([]);
const dnsLoading = ref(false);
const dnsError = ref<string | null>(null);

const isDomainValid = computed(() => {
	if (!domain.value.trim()) return true;
	return isValidDomain(cleanDomain(domain.value));
});

const resolveDomainInfo = async () => {
	if (!domain.value.trim()) return;

	loading.value = true;
	error.value = null;
	domainInfo.value = null;
	dnsRecords.value = [];
	loadingStep.value = '正在解析域名基本信息...';

	try {
		const result = await resolveDomain(domain.value);
		if (result) {
			domainInfo.value = result;
			// 默认加载A记录
			await loadDnsRecords('A');
		} else {
			error.value = '无法解析该域名';
		}
	} catch (err) {
		error.value = err instanceof Error ? err.message : '解析域名时发生错误';
		console.error('Domain resolution error:', err);
	} finally {
		loading.value = false;
		loadingStep.value = '';
	}
};

const loadDnsRecords = async (type: string) => {
	if (!domainInfo.value) return;

	dnsLoading.value = true;
	dnsError.value = null;
	selectedDnsType.value = type;

	try {
		const records = await getDnsRecordByType(domainInfo.value.domain, type);
		dnsRecords.value = records;
	} catch (err) {
		dnsError.value =
			err instanceof Error ? err.message : '获取DNS记录时发生错误';
		console.error('DNS record loading error:', err);
	} finally {
		dnsLoading.value = false;
	}
};

const copyToClipboard = async (text: string) => {
	await navigator.clipboard.writeText(text);
};

const formatDate = (dateString?: string) => {
	if (!dateString) return '未知';
	try {
		return new Date(dateString).toLocaleString('zh-CN');
	} catch {
		return dateString;
	}
};

const getRecordTypeColor = (type: string) => {
	const colors: Record<string, string> = {
		A: 'bg-blue-100 text-blue-800',
		AAAA: 'bg-purple-100 text-purple-800',
		CNAME: 'bg-green-100 text-green-800',
		MX: 'bg-yellow-100 text-yellow-800',
		TXT: 'bg-red-100 text-red-800',
		NS: 'bg-indigo-100 text-indigo-800',
		SOA: 'bg-gray-100 text-gray-800'
	};
	return colors[type] || 'bg-gray-100 text-gray-800';
};

// DNS记录类型选项
const dnsTypeOptions = [
	{ label: 'A记录 (IPv4地址)', value: 'A' },
	{ label: 'AAAA记录 (IPv6地址)', value: 'AAAA' },
	{ label: 'CNAME记录 (别名)', value: 'CNAME' },
	{ label: 'MX记录 (邮件服务器)', value: 'MX' },
	{ label: 'TXT记录 (文本信息)', value: 'TXT' },
	{ label: 'NS记录 (名称服务器)', value: 'NS' },
	{ label: 'SOA记录 (起始授权)', value: 'SOA' }
];
</script>

<template>
	<c-card>
		<div space-y-6>
			<!-- 域名输入 -->
			<div>
				<c-label>域名</c-label>
				<div flex gap-2 mt-2>
					<c-input-text
						v-model:value="domain"
						placeholder="请输入域名，如：example.com"
						flex-1
						:class="{ 'border-red-500': !isDomainValid }"
						@keyup.enter="resolveDomainInfo" />
					<c-button
						@click="resolveDomainInfo"
						:loading="loading"
						:disabled="!domain.trim() || !isDomainValid"
						type="primary">
						解析
					</c-button>
				</div>
				<p v-if="!isDomainValid" text-red-500 text-sm mt-1>
					请输入有效的域名格式
				</p>
			</div>

			<!-- 加载状态 -->
			<div v-if="loading" flex flex-col items-center justify-center py-8>
				<n-spin size="large" />
				<div mt-4 text-center>
					<div text-lg font-medium text-gray-700>
						{{ loadingStep }}
					</div>
					<div text-sm text-gray-500 mt-1>
						正在获取域名基本信息...
					</div>
				</div>
			</div>

			<!-- 错误信息 -->
			<div v-else-if="error" p-4 bg-red-50 border border-red-200 rounded>
				<div flex items-center gap-2>
					<div
						w-5
						h-5
						bg-red-500
						rounded-full
						flex
						items-center
						justify-center>
						<span text-white text-xs>!</span>
					</div>
					<span text-red-700>{{ error }}</span>
				</div>
			</div>

			<!-- 解析结果 -->
			<div v-else-if="domainInfo" space-y-6>
				<!-- 基本信息 -->
				<div>
					<h3 text-lg font-semibold mb-4>基本信息</h3>
					<div grid grid-cols-1 md:grid-cols-2 gap-4>
						<n-statistic label="域名" :value="domainInfo.domain" />
						<n-statistic
							v-if="domainInfo.ipAddresses.length > 0"
							label="IP地址"
							:value="domainInfo.ipAddresses.join(', ')" />
						<n-statistic
							v-else
							label="IP地址"
							:value="'未找到A记录'" />
					</div>
				</div>

				<!-- DNS记录查询 -->
				<div>
					<div flex items-center justify-between mb-4>
						<h3 text-lg font-semibold>DNS记录</h3>
						<div flex items-center gap-3>
							<span text-sm text-gray-600>选择记录类型：</span>
							<n-select
								v-model:value="selectedDnsType"
								:options="dnsTypeOptions"
								placeholder="选择DNS记录类型"
								size="small"
								style="width: 200px"
								@update:value="loadDnsRecords" />
						</div>
					</div>

					<!-- DNS记录加载状态 -->
					<div
						v-if="dnsLoading"
						flex
						items-center
						justify-center
						py-6>
						<n-spin />
						<span ml-2 text-gray-600>
							正在查询{{ selectedDnsType }}记录...
						</span>
					</div>

					<!-- DNS记录错误 -->
					<div
						v-else-if="dnsError"
						p-3
						bg-red-50
						border
						border-red-200
						rounded>
						<div flex items-center gap-2>
							<div
								w-4
								h-4
								bg-red-500
								rounded-full
								flex
								items-center
								justify-center>
								<span text-white text-xs>!</span>
							</div>
							<span text-red-700 text-sm>{{ dnsError }}</span>
						</div>
					</div>

					<!-- DNS记录结果 -->
					<div v-else-if="dnsRecords.length > 0" space-y-3>
						<div
							v-for="record in dnsRecords"
							:key="`${record.type}-${record.name}-${record.value}`"
							bg-gray-50
							p-4
							rounded-lg
							border
							border-gray-200>
							<div flex items-center justify-between>
								<div flex items-center gap-3>
									<span
										:class="getRecordTypeColor(record.type)"
										px-2
										py-1
										rounded
										text-xs
										font-medium>
										{{ record.type }}
									</span>
									<div>
										<div text-sm font-medium text-gray-900>
											{{ record.name }}
										</div>
										<div text-sm text-gray-600 font-mono>
											{{ record.value }}
										</div>
									</div>
								</div>
								<div flex items-center gap-2>
									<div
										v-if="record.ttl"
										text-xs
										text-gray-500>
										TTL: {{ record.ttl }}
									</div>
									<c-button
										size="small"
										@click="copyToClipboard(record.value)">
										复制
									</c-button>
								</div>
							</div>
						</div>
					</div>

					<!-- 无DNS记录 -->
					<div
						v-else
						p-4
						text-center
						text-gray-500
						bg-gray-50
						rounded-lg>
						没有找到{{ selectedDnsType }}记录
					</div>
				</div>

				<!-- WHOIS信息 -->
				<div v-if="domainInfo.whoisInfo">
					<h3 text-lg font-semibold mb-4>WHOIS信息</h3>
					<div grid grid-cols-1 md:grid-cols-2 gap-4>
						<n-statistic
							v-if="domainInfo.whoisInfo.registrar"
							label="注册商"
							:value="domainInfo.whoisInfo.registrar" />
						<n-statistic
							v-if="domainInfo.whoisInfo.creationDate"
							label="创建时间"
							:value="
								formatDate(domainInfo.whoisInfo.creationDate)
							" />
						<n-statistic
							v-if="domainInfo.whoisInfo.expirationDate"
							label="过期时间"
							:value="
								formatDate(domainInfo.whoisInfo.expirationDate)
							" />
						<n-statistic
							v-if="domainInfo.whoisInfo.updatedDate"
							label="更新时间"
							:value="
								formatDate(domainInfo.whoisInfo.updatedDate)
							" />
					</div>

					<div
						v-if="
							domainInfo.whoisInfo.nameServers &&
							domainInfo.whoisInfo.nameServers.length > 0
						"
						mt-4>
						<c-label>名称服务器</c-label>
						<div mt-2 space-y-2>
							<div
								v-for="ns in domainInfo.whoisInfo.nameServers"
								:key="ns"
								flex
								items-center
								justify-between
								bg-gray-50
								p-3
								rounded-lg>
								<span font-mono text-sm>{{ ns }}</span>
								<c-button
									size="small"
									@click="copyToClipboard(ns)">
									复制
								</c-button>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</c-card>
</template> 